package com.web.wx.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.common.tool.Configure;
import com.common.tool.HttpRequest;
import com.common.tool.WeiXinUtil;
import com.dao.MemberBuy;
import com.dao.SysService;
import com.entity.WeiXinPay;
import com.entity.weixin.PayCommonUtil;
import com.entity.weixin.UnifiedOrder;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;

public class WeiXinPayController extends Controller {

    private JSONObject json;
    private boolean flag = false;
    private String msg = "";
    private String spbill_create_ip ;
    
   
    // 回调接口
    private String notify_url = PropKit.get("weixin_area");

    public void weixinpay() throws Exception {
	JSONObject json = new JSONObject();
	spbill_create_ip = this.getPara("spbill_create_ip");
	System.out.println("spbill_create_ip::::"+spbill_create_ip);
	String order_pay = this.getPara("money");// 元
	String body = this.getPara("categoryname");

	String buyId = this.getPara("buyId");

	String seq = null;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	Date date = new Date();
	seq = sdf.format(date);

	String out_trade_no = seq + buyId;
	System.out.println(PayCommonUtil.getCurrentTimeMillis());
	//付的是元为单位，调接口时要转换成分order_price 分
	double pay=Double.parseDouble(order_pay)*100;
	System.out.println(pay);
        DecimalFormat format = new DecimalFormat("#");
        String order_price  = format.format(pay);
	System.out.println(order_price);
	String prepayId = this.getPrepayIdOfcreateOrder(order_price, body, out_trade_no, spbill_create_ip);
	if (prepayId != null) {
	    flag = true;
	    // 更改订单中的微信订单号
	    String updateWeiXinPrepayIdSql = "update member_buy set prepayid='" + prepayId + "' where buyid=" + buyId;
	    MemberBuy memberBuy = new MemberBuy();
	    Db.update(updateWeiXinPrepayIdSql);
	    WeiXinPay weixinpay = this.createParamOfPay(prepayId);
	    json.put("weixinpay", weixinpay);

	} else {
	    msg = "生成微信订单失败！";
	}
	json.put("msg", msg);
	json.put("flag", flag);
	renderJson(json);
    }

    /**
     * 
     * @Title: getPrepayIdOfcreateOrder @Description:
     *         微信统一下单后得到微信支付的订单ID @param @param order_price 价格
     *         注意：价格的单位是分 @param @param body 商品名称 @param @param out_trade_no
     *         订单号 @param @param spbill_create_ip 获取发起电脑 ip @param @return
     *         设定文件 @return String 返回类型 @throws
     */
    private String getPrepayIdOfcreateOrder(String order_price, String body, String out_trade_no,
	    String spbill_create_ip) {
	String prepay_id = null;
	// 账号信息
	String appid = Configure.getAppid(); // appid
	// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
	String mch_id = Configure.getMchid();// 商业号
	String key = Configure.getKey(); // key
	String currTime = PayCommonUtil.getCurrTime();
	String strTime = currTime.substring(8, currTime.length());
	String strRandom = PayCommonUtil.buildRandom(4) + "";
	String nonce_str = strTime + strRandom;
	String trade_type = "JSAPI";
	SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
	packageParams.put("appid", appid);
	packageParams.put("mch_id", mch_id);
	packageParams.put("nonce_str", nonce_str);
	packageParams.put("body", body);
	packageParams.put("out_trade_no", out_trade_no);
	packageParams.put("total_fee", order_price);
	packageParams.put("spbill_create_ip", spbill_create_ip);
	packageParams.put("notify_url", notify_url);
	packageParams.put("trade_type", trade_type);
	packageParams.put("openid", this.getSessionAttr("openId"));
	String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
	packageParams.put("sign", sign);
	String requestXML = PayCommonUtil.getRequestXml(packageParams);
	System.out.println(requestXML);
	String resXml = HttpRequest.sendPost(Configure.PAY_ORDER, requestXML);
	SysService sysSerivce = new SysService();
	sysSerivce.setRemark("out_trade_no:" + out_trade_no);
	sysSerivce.setParameter(requestXML);
	sysSerivce.setResult(resXml);
	sysSerivce.setServicetitle("微信统一下单");
	sysSerivce.setType("weixin");
	sysSerivce.setServicename(Configure.PAY_ORDER);
	sysSerivce.save();
	Map<String, String> payXmlToMap = PayCommonUtil.readStringXmlOut(resXml);
	String return_code = (String) payXmlToMap.get("return_code");
	// System.out.println(resXml);
	// 添加一条操作日志，及返回值

	if (return_code.equalsIgnoreCase("SUCCESS")) {
	    prepay_id = (String) payXmlToMap.get("prepay_id");
	}
	return prepay_id;
    }

    /**
     * 
     * @Title: createParamOfPay @Description: 生成调用支付接口所需的参数 @param @param
     *         prepayId 微信统一下单后的订单id, @param @return 设定文件 @return WeiXinPay
     *         返回类型 @throws
     */
    private WeiXinPay createParamOfPay(String prepayId) {
	String timestamp = String.valueOf(PayCommonUtil.getCurrentTimeMillis());

	String key = Configure.getKey(); // key
	String currTime = PayCommonUtil.getCurrTime();
	String strTime = currTime.substring(8, currTime.length());
	String strRandom = PayCommonUtil.buildRandom(4) + "";
	String nonce_str = strTime + strRandom;

	String packages = "prepay_id=" + prepayId;

	SortedMap secondpackageParams = new TreeMap();
	secondpackageParams.put("appId", Configure.getAppid());
	secondpackageParams.put("timeStamp", timestamp);
	secondpackageParams.put("nonceStr", nonce_str);
	secondpackageParams.put("package", packages);
	secondpackageParams.put("signType", "MD5");

	String paySign = PayCommonUtil.createSign("UTF-8", secondpackageParams, key);

	WeiXinPay weiXinPay = new WeiXinPay();
	weiXinPay.setPrepayId(prepayId);
	weiXinPay.setTimeStamp(timestamp);
	weiXinPay.setNonceStr(nonce_str);
	weiXinPay.setPaypackage(packages);
	weiXinPay.setPaySign(paySign);
	return weiXinPay;

    }

    public void weixinpayjsp() throws Exception {
	// 账号信息
	String appid = Configure.getAppid(); // appid
	// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
	String mch_id = Configure.getMchid();// 商业号
	String key = Configure.getKey(); // key
	String currTime = PayCommonUtil.getCurrTime();
	String strTime = currTime.substring(8, currTime.length());
	String strRandom = PayCommonUtil.buildRandom(4) + "";
	String nonce_str = strTime + strRandom;

	String order_price = "1"; // 价格 注意：价格的单位是分
	String body = "goodssssss"; // 商品名称
	String out_trade_no = "11338"; // 订单号
	// String out_trade_no = this.getPara("buyid");
	// 获取发起电脑 ip
	String spbill_create_ip = "10.10.10.10";
	// 回调接口
	String notify_url = "http://miaowxtest.ngrok.cc/weixin";
	String trade_type = "JSAPI";
	SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
	packageParams.put("appid", appid);
	packageParams.put("mch_id", mch_id);
	packageParams.put("nonce_str", nonce_str);
	packageParams.put("body", body);
	packageParams.put("out_trade_no", out_trade_no);
	packageParams.put("total_fee", order_price);
	packageParams.put("spbill_create_ip", spbill_create_ip);
	packageParams.put("notify_url", notify_url);
	packageParams.put("trade_type", trade_type);
	packageParams.put("openid", "orUWqv9PXkMkWv_ge6P0LD6DxM8Q");

	String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
	packageParams.put("sign", sign);

	String requestXML = PayCommonUtil.getRequestXml(packageParams);
	System.out.println(requestXML);
	String resXml = HttpRequest.sendPost(Configure.PAY_ORDER, requestXML);
	Map<String, String> payXmlToMap = PayCommonUtil.readStringXmlOut(resXml);
	String return_code = (String) payXmlToMap.get("return_code");
	System.out.println(resXml);
	if (return_code.equalsIgnoreCase("SUCCESS")) {
	    // update
	    String timestamp = String.valueOf(PayCommonUtil.getCurrentTimeMillis());
	    String prepay_id = (String) payXmlToMap.get("prepay_id");

	    this.setAttr("prepay_id", prepay_id);
	    this.setAttr("appId", appid);
	    this.setAttr("timeStamp", timestamp);

	    this.setAttr("nonceStr", nonce_str);

	    this.setAttr("signType", "MD5");
	    String prepay_id2 = "prepay_id=" + prepay_id;
	    String packages = prepay_id2;

	    SortedMap secondpackageParams = new TreeMap();
	    secondpackageParams.put("appId", appid);
	    secondpackageParams.put("timeStamp", timestamp);
	    secondpackageParams.put("nonceStr", nonce_str);
	    secondpackageParams.put("package", packages);
	    secondpackageParams.put("signType", "MD5");

	    // "appId="+appId+"&nonceStr="+noncestr +
	    // "&package=prepay_id="+prepay_id+"&signType=MD5&timeStamp="+timestamp+"&key="+key;

	    sign = PayCommonUtil.createSign("UTF-8", secondpackageParams, key);
	    packageParams.put("sign", sign);

	    this.setAttr("paySign", sign);

	    // String packageStr = "\"appid\":\"" + appid + "\"," +
	    // "\"timeStamp\":\"" + timestamp + "\","
	    // + "\"nonceStr\":\"" + nonce_str + "\"," + "\"package\":\"" +
	    // packages + "\"," + "\"signType\":\""
	    // + "MD5\"" + "," + "\"paySign\":\"" + sign + "\"";

	    this.setAttr("paypackage", prepay_id2);

	    System.out.println("paypackage:::::" + this.getAttr("paypackage"));

	    System.out.println(prepay_id);
	}

	renderJsp("/weixin/pay/payindex.jsp");
    }

}
